package cn.lh.org.controller;

import cn.lh.basic.util.JsonResult;
import cn.lh.basic.util.Page;
import cn.lh.org.domain.Department;
import cn.lh.org.query.DepartmentQuery;
import cn.lh.org.service.IDepartmentService;
import cn.lh.system.annotation.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/department")
@RestController
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @GetMapping("/{id}")
    public Department findOne(@PathVariable("id") long id) {
        return departmentService.findById(id);
    }

    @GetMapping
    public List<Department> findAll() {
        return departmentService.findAll();
    }

    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") long id) {
        try {
            departmentService.del(id);
            return JsonResult.set(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "删除失败");
        }

    }

    @PutMapping
    public JsonResult addOrUpdate(@RequestBody Department department) {
        try {
            if (department.getId() == null) {
                departmentService.add(department);
            } else {
                departmentService.update(department);
            }
            return JsonResult.set(true, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "操作失败");
        }

    }

    @PostMapping
    public Page<Department> queryPage(@RequestBody DepartmentQuery query) {
        return departmentService.queryPage(query);
    }

    @PatchMapping
    public JsonResult batchDelete(@RequestBody Long[] ids){
        try {
            departmentService.batchDelete(ids);
            return JsonResult.set(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.set(false, "删除失败");
        }
    }

    @GetMapping("/depttree")
    @PreAuthorize(name = "获取部门树", sn = "department:tree")
    public List<Department> getDepartmentTree(){
        return departmentService.getDepartmentTree();
    }
}
